package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.service.system.AdminService;

import com.qingcheng.service.system.ResourceService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.*;

/**
 * Welcome to the most Amazing IntelliJ IIIDEA.
 * Creat0r: ^_^ fffantianxing ^_^
 * Date: 2019-06-29
 * Time: 12:51
 */
public class UserDetailServiceImpl implements UserDetailsService {

    @Reference
    private AdminService adminService;
    @Reference
    private ResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        Map map = new HashMap();
//        System.out.println(s);
        map.put("loginName", s);
        map.put("status", "1");
        List<Admin> list = adminService.findList(map);
        if (list.size() == 0) {
            return null;
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<String> resKeyList = resourceService.findResKeyByLoginName(s);
        for (String resKey : resKeyList) {
            grantedAuthorities.add(new SimpleGrantedAuthority(resKey));
        }

        System.out.println(grantedAuthorities.toString());
        return new User(s, list.get(0).getPassword(), grantedAuthorities);
    }
}
